package com.example.singing.manager;

import com.example.singing.model.Score;
import com.example.singing.model.Team;
import com.example.singing.model.Competition;
import com.example.singing.util.FileUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Set;

/**
 * 评分管理类
 */
public class ScoreManager {
    private List<Score> scores;
    private static final String SCORE_FILE = "scores.dat";

    public ScoreManager() {
        this.scores = new ArrayList<>();
        loadScores();
        // 移除示例数据，不再自动添加
    }

    /**
     * 添加评分
     */
    public void addScore(Score score) {
        scores.add(score);
        saveScores();
    }

    /**
     * 根据ID获取评分
     */
    public Score getScoreById(String id) {
        for (Score score : scores) {
            if (score.getId().equals(id)) {
                return score;
            }
        }
        return null;
    }

    /**
     * 获取所有评分
     */
    public List<Score> getAllScores() {
        return new ArrayList<>(scores);
    }

    /**
     * 根据比赛ID获取评分
     */
    public List<Score> getScoresByCompetitionId(String competitionId) {
        return scores.stream()
                .filter(s -> s.getCompetitionId().equals(competitionId))
                .collect(Collectors.toList());
    }

    /**
     * 根据队伍ID获取评分
     */
    public List<Score> getScoresByTeamId(String teamId) {
        return scores.stream()
                .filter(s -> s.getTeamId().equals(teamId))
                .collect(Collectors.toList());
    }

    /**
     * 根据比赛和队伍ID获取评分
     */
    public List<Score> getScoresByCompetitionAndTeam(String competitionId, String teamId) {
        return scores.stream()
                .filter(s -> s.getCompetitionId().equals(competitionId) && s.getTeamId().equals(teamId))
                .collect(Collectors.toList());
    }

    /**
     * 保存评分数据
     */
    public void saveScores() {
        FileUtil.saveData(scores, SCORE_FILE);
    }

    /**
     * 加载评分数据
     */
    @SuppressWarnings("unchecked")
    public void loadScores() {
        Object data = FileUtil.loadData(SCORE_FILE);
        if (data != null) {
            scores = (List<Score>) data;
        }
    }

    /**
     * 添加示例数据
     */
    private void addSampleData() {
        scores.add(new Score("SCORE_SAMPLE_001", "COMP001", "TEAM_SAMPLE_001", Arrays.asList(9.0, 8.5, 9.2, 8.8, 9.5), 9.0));
        scores.add(new Score("SCORE_SAMPLE_002", "COMP001", "TEAM_SAMPLE_002", Arrays.asList(8.5, 8.7, 8.9, 9.1, 8.6), 8.7));
        scores.add(new Score("SCORE_SAMPLE_004", "COMP001", "TEAM_SAMPLE_004", Arrays.asList(8.8, 9.0, 8.6, 8.9, 9.1), 8.9));
        saveScores();
    }
    
    /**
     * 根据ID删除评分
     */
    public boolean deleteScoreById(String id) {
        System.out.println("尝试删除评分ID: " + id);
        System.out.println("删除前评分总数: " + scores.size());
        
        // 先尝试从内存中删除评分
        boolean removed = scores.removeIf(score -> {
            boolean shouldRemove = score.getId().equals(id);
            if (shouldRemove) {
                System.out.println("找到要删除的评分: " + score.getId() + 
                                 ", 比赛ID: " + score.getCompetitionId() + 
                                 ", 队伍ID: " + score.getTeamId());
            }
            return shouldRemove;
        });
        
        System.out.println("删除操作结果: " + removed);
        System.out.println("删除后评分总数: " + scores.size());
        
        if (removed) {
            // 确保数据保存到文件中
            try {
                saveScores();
                System.out.println("评分数据已保存到文件");
                // 不需要重新加载数据，保持内存中的状态一致
            } catch (Exception e) {
                System.err.println("删除评分后保存数据失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
        return removed;
    }
    
    /**
     * 清理无效的评分数据
     */
    public void cleanInvalidScores(TeamManager teamManager, CompetitionManager competitionManager) {
        System.out.println("开始清理无效评分数据...");
        System.out.println("清理前评分总数: " + scores.size());
        
        // 获取所有有效的队伍ID和比赛ID
        Set<String> validTeamIds = teamManager.getAllTeams().stream()
                .map(Team::getId)
                .collect(Collectors.toSet());
        
        Set<String> validCompetitionIds = competitionManager.getAllCompetitions().stream()
                .map(Competition::getId)
                .collect(Collectors.toSet());
        
        System.out.println("有效队伍ID数量: " + validTeamIds.size());
        System.out.println("有效比赛ID数量: " + validCompetitionIds.size());
        
        // 删除引用不存在队伍或比赛的评分
        boolean removed = scores.removeIf(score -> {
            boolean invalidTeam = !validTeamIds.contains(score.getTeamId());
            boolean invalidCompetition = !validCompetitionIds.contains(score.getCompetitionId());
            
            if (invalidTeam || invalidCompetition) {
                System.out.println("发现无效评分: " + score.getId() + 
                                 ", 无效队伍: " + invalidTeam + 
                                 ", 无效比赛: " + invalidCompetition);
                return true;
            }
            return false;
        });
        
        if (removed) {
            System.out.println("已清理无效评分数据");
            saveScores();
        }
        
        System.out.println("清理后评分总数: " + scores.size());
    }
}